package com.keyancompany.zhongbaopingtai.activity;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.adapter.IFragmentPagerAdapter;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.fragment.FindFragment;
import com.keyancompany.zhongbaopingtai.fragment.MessageFragment;
import com.keyancompany.zhongbaopingtai.fragment.MineFragment;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.EventBusEntity;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.utils.SPUtils;
import com.keyancompany.zhongbaopingtai.utils.T;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.BindString;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;

    @BindString(R.string.app_name)
    String appName;

    @Bind(R.id.common_page)
    ViewPager commonPage;

    @Bind(R.id.main_menu_parent)
    RadioGroup mainMenuParent;


    private List<Fragment> mFragmentList = new ArrayList<Fragment>();

    private MessageFragment messageFragment;

    private MineFragment mineFragment;

    private FindFragment findFragment;

//    private TeamFragment teamFragment;

    private IFragmentPagerAdapter mFragmentAdapter;

    private int currentIndex = 0;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected int getMenuId() {
        return R.menu.base_toolbar_menu;
    }

    @Override
    protected void initToolBar() {
        initToolBar(toolbar, appName);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

    @Override
    protected void setUpViews() {

        EventBus.getDefault().register(this);
        mainMenuParent.check(R.id.mine_radio);

        mineFragment = new MineFragment();
        messageFragment = new MessageFragment();
        findFragment = new FindFragment();
//        teamFragment = new TeamFragment();
        mFragmentList.add(mineFragment);
        mFragmentList.add(messageFragment);
        mFragmentList.add(findFragment);
//        mFragmentList.add(teamFragment);

        mFragmentAdapter = new IFragmentPagerAdapter(
                this.getSupportFragmentManager(), mFragmentList);
        commonPage.setAdapter(mFragmentAdapter);
        commonPage.setOffscreenPageLimit(5);
        commonPage.setCurrentItem(0);
        setUpListener();
        initData();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_friend:
                IntentUtils.startActivity(mContext, FriendsActivity.class);
                break;
            case R.id.action_search:
//                        IntentUtils.startActivity(mContext, FriendsActivity.class);
                break;
            case R.id.action_setting:
                IntentUtils.startActivity(mContext, SysSettingActivity.class);
                break;
        }
        return true;

    }


    /**
     * 事件订阅者自定义的接收方法
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
//        //（1）将事件发布者发布的数据作为文本修改内容
//        msgFragment.setText(event.data);
        //（2）将事件发布者发布的数据作为方法执行的区分
        switch (event.getType()) {
            case EventBusEntity.Type.HEAD:
                if (mineFragment != null) {
                    mineFragment.updateData();
                }
                break;
            case EventBusEntity.Type.USERNAME:
                if (mineFragment != null) {
                    mineFragment.updateData();
                }
                break;
        }
    }

    private void initData() {
        if (isNetvaiable()) {
            UserAPI.userInfo(MainActivity.this,
                    getLoading(R.string.watting_hint));
        }
    }

    @Override
    public void success(int type, String json) {
        super.success(type, json);
        switch (type) {
            case UserAPI.UESER_INFO_CODE:
                BaseModel base = validateJson(json);
                if (base != null) {
                    SPUtils.putCommData(this, Constants.USER, base.data);
                    mineFragment.updateData();
                }
                break;
        }
    }

    @Override
    public void failed(String error) {
        super.failed(error);
        T.showShort(mContext, error);
    }


    public void setUpListener() {
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.action_friend:
                        IntentUtils.startActivity(mContext, FriendsActivity.class);
                        break;
                    case R.id.action_search:
//                        IntentUtils.startActivity(mContext, FriendsActivity.class);
                        break;
                    case R.id.action_setting:
                        IntentUtils.startActivity(mContext, SysSettingActivity.class);
                        break;
                }
                return true;
            }
        });
        commonPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            /**
             * position :当前页面，及你点击滑动的页面 offset:当前页面偏移的百分比
             * offsetPixels:当前页面偏移的像素位置
             */
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }


            @Override
            public void onPageSelected(int position) {
                currentIndex = position;
                Menu itemMenu = toolbar.getMenu();
                if (currentIndex == 0) { //设置
                    itemMenu.findItem(R.id.action_search).setVisible(false);
                    itemMenu.findItem(R.id.action_friend).setVisible(false);
                    itemMenu.findItem(R.id.action_setting).setVisible(true);
                } else if (currentIndex == 1) { //好友
                    itemMenu.findItem(R.id.action_search).setVisible(false);
                    itemMenu.findItem(R.id.action_setting).setVisible(false);
                    itemMenu.findItem(R.id.action_friend).setVisible(true);
                } else if (currentIndex == 2) { //发现
                    itemMenu.findItem(R.id.action_search).setVisible(false);
                    itemMenu.findItem(R.id.action_setting).setVisible(false);
                    itemMenu.findItem(R.id.action_friend).setVisible(false);
                } else {
                    itemMenu.findItem(R.id.action_search).setVisible(false);
                    itemMenu.findItem(R.id.action_setting).setVisible(false);
                    itemMenu.findItem(R.id.action_friend).setVisible(false);
                }

                mainMenuParent.check(mainMenuParent.getChildAt(position).getId());
            }

            /**
             * state滑动中的状态 有三种状态（0，1，2） 1：正在滑动 2：滑动完毕 0：什么都没做。
             */
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mainMenuParent.setOnCheckedChangeListener(this);
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (currentIndex == 0) { //设置
            menu.findItem(R.id.action_search).setVisible(false);
            menu.findItem(R.id.action_friend).setVisible(false);
            menu.findItem(R.id.action_setting).setVisible(true);
        } else if (currentIndex == 1) { //好友
            menu.findItem(R.id.action_search).setVisible(false);
            menu.findItem(R.id.action_setting).setVisible(false);
            menu.findItem(R.id.action_friend).setVisible(true);
        } else if (currentIndex == 2) { //查找
            menu.findItem(R.id.action_search).setVisible(false);
            menu.findItem(R.id.action_setting).setVisible(false);
            menu.findItem(R.id.action_friend).setVisible(false);
        } else {
            menu.findItem(R.id.action_search).setVisible(false);
            menu.findItem(R.id.action_setting).setVisible(false);
            menu.findItem(R.id.action_friend).setVisible(false);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.mine_radio:
                commonPage.setCurrentItem(0);
                break;
            case R.id.message_radio:
                commonPage.setCurrentItem(1);
                break;
            case R.id.find_radio:
                commonPage.setCurrentItem(2);
                break;
            case R.id.team_radio:
                commonPage.setCurrentItem(3);
                break;
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        exitByDoubleClick();
    }

    boolean isExit = false;

    private void exitByDoubleClick() {
        Timer tExit = null;
        if (!isExit) {
            isExit = true;
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;//取消退出
                }
            }, 2000);// 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
